package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.util.UUIDUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: qingtao
 * @Date 2022/3/23 18:03
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired(required = false)
    private AddressBookMapper addressBookMapper;

    @Autowired(required = false)
    private OrderMapper orderMapper;

    @Autowired(required = false)
    private OrderDetailMapper orderDetailMapper;
    /**
     * 作用： 下单
     *
     * @param orders 订单的信息（地址id，支付方式，备注）
     * @param userId
     * @return
     * @Param userId  当前的登陆者
     */
    @Override
    @Transactional
    public void submit(Orders orders, Long userId) {
        //A. 获得当前用户id, 查询当前用户的购物车数据
        List<ShoppingCart> cart = shoppingCartMapper.findCartByUserId(userId);
        //B. 根据当前登录用户id, 查询用户数据
        User user = userMapper.findById(userId);
        //C. 根据地址ID, 查询地址数据
        AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());

        //声明变量记录总金额
        BigDecimal totalAmount = new BigDecimal("0");

        //D. 组装订单数据, 批量保存订单数据
        Long oid = new Long(UUIDUtils.getUUIDInOrderId());
        orders.setId(oid);
        orders.setNumber(oid+"");
        orders.setStatus(1);  //1待付款
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now()); //下单时间
        orders.setCheckoutTime(LocalDateTime.now()); //结账时间

        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setUserName(user.getName());  //登录用户的别名
        orders.setConsignee(addressBook.getConsignee()); //收件人

        //E. 组装订单明细数据, 批量保存订单明细
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : cart) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setId(new Long(UUIDUtils.getUUIDInOrderId()));
            orderDetail.setName(shoppingCart.getName()); //菜品名字或套餐名字
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setOrderId(orders.getId());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());
            //将封装好的orderDeail对象加入到orderDetailList
            orderDetailList.add(orderDetail);

            //累加每个商品的金额=数量*单价
            //multiply() 这个是decimal类型的乘法方法
            //add() 这个是decimal类型的加法方法
            totalAmount = totalAmount.add(orderDetail.getAmount().multiply(new BigDecimal(orderDetail.getNumber()+"")));
        }

        //注意：完善订单主表的总价
        orders.setAmount(totalAmount);

        //5.调用mapper新增订单主表数据
        orderMapper.save(orders);
        //6.调用mapper新增多条订单明细表数据
        orderDetailMapper.saveBatch(orderDetailList);
        //F. 删除当前用户的购物车列表数据
        shoppingCartMapper.clear(userId);
    }

//    /**
//     * 分页查询
//     *
//     * @param page
//     * @param pageSize
//     * @return
//     */

    /**
     * 用户查询
     *
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public Page<OrderDto> findByUserPage(Integer page, Integer pageSize, Long userId,Long id) {

        //设置分页大小
        PageHelper.startPage(page, pageSize);
        //获得数据库的数据列表
        List<Orders> orders = orderMapper.findByPage(id,userId);
        //创建分页
        PageInfo<Orders> pageInfo = new PageInfo<>(orders);

        List<OrderDto> orderDtoList = orders.stream().map((order -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(order,orderDto);
            List<OrderDetail> detailList = orderDetailMapper.findByOrderId(orderDto.getId());
            orderDto.setOrderDetails(detailList);
            return orderDto;
        })).collect(Collectors.toList());
        Page<OrderDto> objectPage = new Page<>();
        objectPage.setTotal(pageInfo.getTotal());
        objectPage.setPageSize(pageInfo.getPageNum());
        objectPage.setPage(pageInfo.getPages());
        objectPage.setRecords(orderDtoList);
        return objectPage;
    }
}
